<?php
/*
 * 图片
 * */

namespace app\common;



class Images
{
    /**
     * 生成区域文字
     * @param string $text 文本内容
     * @param int $fontSize 字体大小
     * @param string $fontFile 字体文件
     * @param string $color 文字颜色
     * @param int $width 预设宽度
     * @param int $height 预设高度
     * @param string $saveName
     * @param int $interLine 文本行高
     * @param int $fontAngle 角度
     * @param string $charset 编码
     * @return bool
     * @throws /\Exception
     */
    public static function textImage(string $text,int $fontSize,string $fontFile,string $color,int $width,int $height,string $saveName,int $interLine=5,int $fontAngle=0,string $charset='utf-8'):bool
    {
        try {
            $top = 0;
            $left = 0;
            $text = self::autoWrap($fontSize, $fontFile, $text, $width - 2, $fontAngle, $charset);
            $canvas = new \Imagick();
            $canvas->newImage($width, $height, 'rgba(255,255,255,0)', 'png');
            $canvas->setImageFormat('png');
            $draw = new \ImagickDraw();
            $draw->setFontSize($fontSize);//设置字体大小
            $draw->setFillColor(new \ImagickPixel($color));//设置字体颜色
            $draw->setTextInterLineSpacing($interLine);//设置字体行高
            $draw->setFont($fontFile);
            $canvas->annotateImage($draw, $left, ($fontSize + 2) + $top, 0, $text);
            $canvas->writeImage($saveName);
            $canvas->destroy();
            $draw->destroy();
            return true;
        }catch (\Exception $e){
            return false;
        }
    }
    /*
     * 画线
     * width
     * height
     * color
     * saveName
     */
    public static function drawLine(int $width,int $height,string $saveName,string $color='#000000'):bool
    {
        try {
            $img = new \Imagick();
            $img->newImage($width, $height, $color, 'png');
            $img->writeImage($saveName);
            $img->destroy();
            return true;
        }catch (\Exception $e){
            return false;
        }
    }

    /*
     * 圆角图片
     * @param strimg $imgPath 图片路径
     * @param strimg $saveName 图片保存路径
     * @param int $width 图片宽度
     * @param int $height 图片高度
     * @param int $rx x轴半径
     * @param int $ry y轴半径
     * */
    public static function roundRectangle(string $imgPath,string $saveName,int $width,int $height,int $rx = 0,int $ry = 0){
        try {
            $rx = $rx ?: $width / 2;
            $ry = $ry ?: $height / 2;
            $mask = new \Imagick();
            $mask->newImage($width, $height, 'rgba(255,255,255,0)', 'png');
            //$mask->writeImage($saveName);
            if($imgPath){
                $shape = new \ImagickDraw();
                $shape->setFillColor(new \ImagickPixel('#000000'));
                $shape->roundRectangle(0, 0, $width, $height, $rx, $ry);
                $mask->drawImage($shape);
                $image = new \Imagick($imgPath);
                $image->compositeImage($mask, 17, 0, 0);
                $image->writeImage($saveName);
                $image->destroy();
                $shape->destroy();
            }else{
                $mask->writeImage($saveName);
            }
            $mask->destroy();

        }catch (\Exception $e){
            return false;
        }
    }

    /*
     * 保存远程图片
     *
     * */
    public static function getNetImage(string $url,string $saveName):void
    {
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'Accept-Language: zh-CN,zh;q=0.9','Cookie: __guid=4908278.2722325129793157000.1607928194897.848; monitor_count=3',
            'Accept-Encoding: gzip, deflate,br'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);

        //base64则解密
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $data, $result))
        {
            $data = base64_decode(str_replace($result[1], '', $data));
        }

        file_put_contents($saveName, $data);

        curl_close($curl);
    }

    /*
     *  返回一个字符的数组
     * @param $str 文字
     * @param $charset 字符编码
     */

    public static function charArray(string $str,string $charset="utf-8"):array
    {
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        return $match;
    }

    /*
     * 返回一个字符串的宽度 px
     * @param $fontsize  字体大小
     * @param $fontangle 角度
     * @param $ttfpath   字体文件
     * @param $char      字符
     */

    public static function charWidth(int $fontsize,int $fontAngle,string $ttfPath,string $char):float
    {

        $box = @imagettfbbox($fontsize,$fontAngle,$ttfPath,$char);

        return round(max($box[2], $box[4]) - min($box[0], $box[6]),2);

    }



    /*
     * 根据预设宽度让文字自动换行
     * @param $fontsize   字体大小
     * @param $ttfpath    字体名称
     * @param $str    字符串
     * @param $width    预设宽度
     * @param $fontangle  角度
     * @param $charset    编码
     */

    public static function autoWrap($fontsize,$ttfpath,$str,$width,$fontangle=0,$charset='utf-8'){

        $_string = "";

        $temp_str = "";

        $temp    = self::charArray($str,$charset);

        foreach ($temp[0] as $k=>$v){
            $temp_str .= $v;
            $w = self::charWidth($fontsize,$fontangle,$ttfpath,$temp_str);

            if ($w >= $width){
                $_string .= PHP_EOL;
                $temp_str = $v;
            }
            $_string .= $v;

        }

        return $_string;

    }

}

